package tech.senri.iot.socket.service.socket

import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
import tech.senri.iot.socket.model.RequestMessage

class MessageEncoder : MessageToByteEncoder<RequestMessage>()
{
    override fun encode(ctx: ChannelHandlerContext?, msg: RequestMessage, out: ByteBuf)
    {
        /**
         * 板卡类型
         */
        out.writeByte(0x01)
        /**
         * 帧类型
         */
        out.writeByte(msg.messageCode)
        /**
         * 帧长度
         */
        if (msg.messageCode != 0x70)
            out.writeShort(msg.contentData().size + 14)
        else out.writeShort(msg.contentData().size + 13)
        /**
         * 服务器编号
         */
        out.writeByte(0x01)

        /**
         * 功能码
         */
        if (msg.messageCode != 0x70)
            out.writeByte(msg.funCode)
        /**
         * 数据
         */
        out.writeBytes(msg.contentData())
        /**
         * 时间戳
         */
        out.writeBytes(msg.dateTimeData)
        /**
         * 帧尾
         */
        out.writeBytes(byteArrayOf(0x0d, 0x0a))
    }
}
